package net.adriana.ui;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import net.adriana.Fac;
import net.adriana.component.*;
import net.adriana.dao.SchemaDao;

public class LoginWindow extends MyFrame{
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -4449172808192630314L;
	
	private JTextField schemaField;
	private JTextField userField;
	private JPasswordField passwordField;
	private String schema;
	private String user;
	private String password;

	public LoginWindow() {
		super(300, 280);
		draw();
		add(content);
		addTextField();
		addBtn();
		setVisible(true);
	}

	public void addTextField(){
		schemaField = new JTextField();
		schemaField.setBounds(120, 70,120,25);
		userField = new JTextField();
		userField.setBounds(120, 110,120,25);
		passwordField = new JPasswordField();
		passwordField.setBounds(120, 150,120,25);
		content.add(schemaField);
		content.add(userField);
		content.add(passwordField);
	}
	public void addBtn(){
		MyButton btn = new MyButton("登录");
		btn.setBounds(300/2-70/2,200,70,25);
		btn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				schema = schemaField.getText();
				user = userField.getText();
				password = new String(passwordField.getPassword());
				if(schema.equals("")) schema = null;
				if(user.equals("")) user = null;
				if(password.equals("")) password = null;
				SchemaDao dao = new SchemaDao();
				if(dao.login(schema, user, password)){
					Fac.first = new FirstWindow();
					Fac.currentWindow = Fac.first;
					Fac.first.addPreviousBtn();
					Fac.first.addNextBtn();
					Fac.first.addExitBtn();
					Fac.first.repaint();
					dispose();
				}else{
					alertError();
				}
			}
		});
		content.add(btn);
	}
	public void draw(){
		content = new MyPanel(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			public void paint(Graphics g){
				super.paint(g);
				g.setFont(new Font(Font.SERIF,Font.PLAIN,16));
				g.drawString("数据库登录", 110, 40);
				g.setFont(new Font(Font.SERIF,Font.PLAIN,14));
				g.drawString("数据库：", 65, 85);
				g.drawString("用户名：", 65, 125);
				g.drawString("密码：", 65, 165);
			}
		};
		content.setLayout(null);
	}
	
	public void alertError(){
		JOptionPane.showMessageDialog(
				null, 
				"数据库登录失败，请重试", 
				"登录失败",
				JOptionPane.ERROR_MESSAGE);
	}
}
